package com.mxpio.erp.purchase.service.impl;

import com.mxpio.erp.common.jpa.model.OrderLineKey;
import com.mxpio.erp.common.purchase.entity.BuyRequestOrderLine;
import com.mxpio.erp.common.purchase.entity.PurchaseOrder;
import com.mxpio.erp.common.purchase.entity.PurchaseOrderLine;
import com.mxpio.erp.common.purchase.entity.Supply;
import com.mxpio.erp.common.purchase.service.PurchaseOrderService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class PurchaseOrderServiceImpl extends BaseServiceImpl<PurchaseOrder> implements PurchaseOrderService {
    @Override
    @Transactional
    public Result<List<PurchaseOrder>> getPrintsListByIds(String bizNos) {
        String[] split = bizNos.split(",");
        List<String> bizNoList = Stream.of(split).collect(Collectors.toList());
        List<PurchaseOrder> list = JpaUtil.linq(PurchaseOrder.class)
                .collect("bizNo", PurchaseOrderLine.class, "bizNo")
                .collect("pnCode", Supply.class, "pnCode")
                .in("bizNo", bizNoList).list();
        if (list.size()>0){
            for (PurchaseOrder order:list){
                List<PurchaseOrderLine> purchaseOrderLines = order.getPurchaseOrderLine();
                if (CollectionUtils.isNotEmpty(purchaseOrderLines)){
                    for (PurchaseOrderLine poline:purchaseOrderLines){
                        if (StringUtils.isNotBlank(poline.getReqLineNo())){
                            OrderLineKey orderLineKey = new OrderLineKey();
                            orderLineKey.setBizNo(poline.getReqBizNo());
                            orderLineKey.setLineNo(poline.getReqLineNo());
                            BuyRequestOrderLine buyRequestOrderLine = JpaUtil.getOne(BuyRequestOrderLine.class, orderLineKey);
                            if (buyRequestOrderLine!=null){
                                poline.setBRSuggestOrderDate(buyRequestOrderLine.getSuggestOrderDate());
                                poline.setBRArriveDate(buyRequestOrderLine.getArriveDate());
                            }
                        }
                    }
                }
            }
        }
        return Result.OK(list);
    }
}
